import {createRouter, createWebHashHistory, createWebHistory, RouteRecordRaw} from 'vue-router';
import {Tool} from "@/utils/tool";
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import {ROURCE_TYPE} from "@/utils/enums";
import {useStore} from "vuex";
import permissions from "@/store/modules/permissions";
import {RouterView} from "vue-router";

//路由常量
export const constantRoutes = [
    {
        path: '/',
        redirect: '/login'
    },
    {
        path: '/index',
        redirect: '/admin/dashboard'
    }
    , {
        path: '/admin',
        component: resolve => import('@/components/common/Home.vue'),
        name: "admin",
        meta: {
            loginRequire: true
        },
        children: [
            {
                path: '/:pathMatch(.*)',
                component: resolve => import('@/views/404.vue'),
                meta: {title: '404'}
            }
        ]
    },
    {
        path: '/:pathMatch(.*)',
        component: resolve => import('@/views/404.vue'),
        meta: {title: '404'}
    },
    {
        path: '/login',
        component: resolve => import('@/views/Login.vue'),
        meta: {title: '登录'}
    }]

// 匹配view里面所有的.vue文件
const modules = import.meta.glob('./../views/admin/**/*.vue')
const isresourcesCached=(resources:any):Boolean=>{
       return (resources["isCached"]==undefined||resources["isCached"]=="1")?true:false
}
export function getrouterList(url, resources) {
    if (resources != undefined) {
        for (let i = 0; i < resources.length; i++) {
            //  如果不是按钮
            var item: any = {}
            if (resources[i].category != ROURCE_TYPE.BUTTON.key) {
                if (resources[i].parent == '' && resources[i]["children"] == null&&resources[i].path!=null) {
                    let component = '../views' + resources[i].path + '.vue';
                    url.push({
                        path: resources[i].page,
                        name: resources[i].page,
                        component: modules[component],
                        meta: {title: resources[i].name, loginRequire: true, keepAlive: isresourcesCached(resources[i])}
                    })
                } else if (resources[i].parent == '' && resources[i]["children"] != null) {
                    if (resources[i].page != null && resources[i].path != null) {
                        let component = '../views' + resources[i].path + '.vue';
                        item = {
                            path: resources[i].page,
                            name: resources[i].page,
                            component: modules[component],
                            meta: {title: resources[i].name, btnPermissions: [], loginRequire: true, keepAlive:isresourcesCached(resources[i])}
                        }
                        for (let j = 0; j < resources[i].children.length; j++) {
                            if (resources[i].children[j].category == ROURCE_TYPE.BUTTON.key) {
                                item.meta.btnPermissions.push(resources[i].children[j].perms)
                            }
                        }

                    } else if (resources[i].page != null && (resources[i].path == null || resources[i].path == "")) {
                        item = {
                            path: resources[i].page,
                            name: resources[i].page,
                            meta: {title: resources[i].name, btnPermissions: [], loginRequire: true, keepAlive:isresourcesCached(resources[i]) },
                            // component:  RouterView,
                        }
                    }
                    url.push(item)
                } else if (resources[i].parent != '') {
                    if ((resources[i].path != null || resources[i].path != "")) {
                        let component = `../views${resources[i].path}.vue`;
                        item = {
                            path: resources[i].page,
                            name: resources[i].page,
                            meta: {title: resources[i].name, btnPermissions: [], loginRequire: true, keepAlive: isresourcesCached(resources[i])},
                            component: modules[component],
                        }
                    } else {
                        item = {
                            path: resources[i].page,
                            name: resources[i].page,
                            meta: {title: resources[i].name, btnPermissions: [], loginRequire: true, keepAlive: isresourcesCached(resources[i])},
                            // component:   RouterView,
                        }
                    }
                    if (resources[i].children != null) {
                        for (let k = 0; k < resources[i].children.length; k++) {
                            item.meta.btnPermissions.push(resources[i].children[k].perms)
                        }
                    }
                    url.push(item);
                }
                if (resources[i]["children"] != null) {
                    let refchildren = []
                    for (let j = 0; j < resources[i].children.length; j++) {
                        //过滤按钮
                        if (resources[i].children[j].category != ROURCE_TYPE.BUTTON.key) {
                            refchildren.push(resources[i].children[j])
                        }
                    }
                    if (refchildren.length > 0) {
                        url[url.length - 1].children = []
                        getrouterList(url[url.length - 1].children, refchildren);
                    }
                }

            }

        }
    }
    return url;
}

let dynamicrouter = []
getrouterList(dynamicrouter, Tool.getInstance().getLoginUser().resources)

async function addrouterList() {
    dynamicrouter.forEach((itemRouter) => {
        router.addRoute("admin", itemRouter);
        router.options.routes[2].children.push(itemRouter);
    })
}

const router = createRouter({
    history: createWebHistory(),
    routes: constantRoutes
});


export const loadView = (view) => {
    let res;
    for (const path in modules) {
        const dir = path.split('views')[1].split('.vue')[0];
        if (dir.indexOf(view) != -1)
            res = () => modules[view]();
    }
    return res;
}


// 路由登录拦截
router.beforeEach(async (to, from, next) => {
    // 要不要对meta.loginRequire属性做监控拦截
    NProgress.configure({showSpinner: false})
    NProgress.start()
    let store = useStore();
    let loginUser = Tool.getInstance().getLoginUser();
    if (to.matched.some(function (item: any) {
        return item.meta.loginRequire
    })) {
        if (Tool.getInstance().isEmpty(loginUser)) {
            next('/login');
            NProgress.done()
        } else {
            if (store.state.permissions.addRoutes.length > 0) {
                next() //有的话直接跳转
            } else { //不满足条件的话,重新请求后端动态路由数据
                await addrouterList();
                await store.dispatch("permissions/GenerateRoutes", dynamicrouter)
                next({
                    ...to,
                    replace: true
                })
            }
        }
    } else {

        if (!Tool.getInstance().isEmpty(loginUser)) {
            if (store.state.permissions.addRoutes.length > 0) {
                next() //有的话直接跳转
            } else { //不满足条件的话,重新请求后端动态路由数据
                await addrouterList();
                await store.dispatch("permissions/GenerateRoutes", dynamicrouter)
                next({
                    ...to,
                    replace: true
                })
                // next();
            }
        } else {
            next();
        }
    }
});
router.afterEach(() => {
    NProgress.done()
})

export default router;
